import 'dart:convert';
import 'dart:io';

import 'package:demo/app/widgets/CommonDialog.dart';
import 'package:demo/app/widgets/line_horizontal.dart';
import 'package:demo/utils/sp_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../model/identity_model.dart';
import '../../../../net/api_provider.dart';
import '../../../../model/file_model.dart' as FileBean;
import '../../../../theme/app_text_theme.dart';

class IdInfoController extends GetxController {

  var platform = const MethodChannel("sing.top/rth");
  ApiProvider apiProvider = Get.find();

  @override
  void onInit() {
    super.onInit();
    platform.setMethodCallHandler(flutterMethod);
    if(GetPlatform.isAndroid){
      EasyLoading.show();
      platform.invokeMethod('initOCR');
    }
  }

  @override
  void onReady() {
    super.onReady();
    getUserInfo();
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'initOcrOk': // OCR初始化成功
        EasyLoading.dismiss();
        break;
      case 'initOcrError': // OCR初始化失败
        EasyLoading.dismiss();
        Map<dynamic, dynamic> data = methodCall.arguments; // {"msg":""}
        EasyLoading.showToast(data['msg']);
        break;
      case 'showLoading': // 展示loading
        EasyLoading.show();
        break;
      case 'dismissLoading': // 展示loading
        EasyLoading.dismiss();
        break;
      case 'scanIdCardOver': // 身份证识别结束
        // {
        //   "error_message":"错误信息，为空代表识别成功，必须有相关字段",
        //   "is_front":true,                                         // bool值，是否为人像面
        //   "id_number":"身份证号",
        //   "real_name":"姓名",
        //   "address":"地址",
        //   "gender":"性别",
        //   "nation":"民族",
        //   "birthday":"生日",
        //   "issued_by":"发证机关",
        //   "valid_date":"有效期，-连接",
        // }
        Map<dynamic, dynamic> data = methodCall.arguments;
        String errorMsg = data['error_message'] ?? '';
        if(errorMsg.isNotEmpty){ // 报错了
          EasyLoading.showToast(errorMsg);
          return;
        }
        bool isFront = data['is_front'] ?? true;
        if(isFront){
          idNumber = data['id_number'] ?? '';
          realName = data['real_name'] ?? '';
          address = data['address'] ?? '';
          gender = data['gender'] ?? '';
          nation = data['nation'] ?? '';
          birthDay = data['birthday'] ?? '';
        }else{
          issuedBy = data['issued_by'] ?? '';
          validDate = data['valid_date'] ?? '';
        }
        var imagePath = data['image_path'] ?? '';
        uploadImg(imagePath,isFront);
        break;
    }
  }


  // 上传图片
  void uploadImg(String filePath,bool isFront) async {
    // List<int> data = base64.decode(dec_image);

    // final currentTime = DateTime.now();
    // int timestamp = currentTime.millisecondsSinceEpoch;
    // // 创建临时文件
    // final tempDir = await getTemporaryDirectory();
    // final filePath = '${tempDir.path}/$timestamp.png';
    final file = File(filePath);
    // 将数据写入文件
    // await file.writeAsBytes(data);

    var result = await apiProvider.uploadImg(file);
    if(result.code == 200){
      var file = FileBean.File.fromJson(result.data);
      if(isFront){
        idFrontUrl.value = file.url;
      }else{
        idBackUrl.value = file.url;
      }
      EasyLoading.dismiss();
      EasyLoading.showToast('上传成功');
    }else{
      EasyLoading.dismiss();
      EasyLoading.showToast('${result.msg}');
    }
  }

  var idFrontUrl = ''.obs;
  var idBackUrl = ''.obs;
  var idNumber = '';
  var realName = '';
  var address = '';
  var gender = '';
  var nation = '';
  var birthDay = '';
  var issuedBy = '';
  var validDate = '';

  /// 获取个人信息
  void getUserInfo() async {
      var result = await apiProvider.getData({}, ApiProvider.identity);
      if(result.code == 200){
        var identity = Identity.fromJson(result.data);
        idFrontUrl.value = identity.frontImage;
        idBackUrl.value = identity.backImage;
        idNumber = identity.identityNum;
        realName = identity.realName;
        address = identity.address;
        gender = identity.gender;
        nation = identity.nation;
        birthDay = identity.birthDay;
        issuedBy = identity.issuedBy;
        validDate = identity.validDate;
    }
  }

  @override
  void onClose() {
    super.onClose();
    if(GetPlatform.isAndroid){ // 释放OCR
      platform.invokeMethod('releaseOCR');
    }
  }

  /// 提交
  void submit() async {
    if (idFrontUrl.value.isEmpty){
      EasyLoading.showToast('请上传头像面照片');
      return;
    }
    if(idNumber.isEmpty || realName.isEmpty || gender.isEmpty || address.isEmpty || nation.isEmpty || birthDay.isEmpty){
      EasyLoading.showToast('请重新上传头像面照片');
      idFrontUrl.value = '';
      return;
    }
    if (idBackUrl.value.isEmpty){
      EasyLoading.showToast('请上传国徽面照片');
      return;
    }
    if(issuedBy.isEmpty || validDate.isEmpty){
      EasyLoading.showToast('请重新上传国徽面照片');
      idBackUrl.value = '';
      return;
    }

    nameController.text = realName;
    idController.text = idNumber;

    Get.dialog(
        CommonDialog(
          contentWidget: getContent(),
          yesStr: '确认提交',
          noStr: '重新上传',
          yesFun: toRequest,
        )
    );
  }

  TextEditingController nameController = TextEditingController();
  TextEditingController idController = TextEditingController();
  Widget getContent(){
    return Column(
      crossAxisAlignment : CrossAxisAlignment.start,
      mainAxisSize : MainAxisSize.min,
      children: [
        Text('请确认您的实名信息',style: text_grey_14),
        SizedBox(height: 15.w),
        TextField(
          controller: nameController,
          style: text_131732_14,
          decoration: InputDecoration(
            prefixText: "  ",
            isDense: true,
            contentPadding: EdgeInsets.symmetric(vertical: 9.w),
            counterText: "", // 去掉底部计数
            enabledBorder:  const UnderlineInputBorder(borderSide: BorderSide.none), //无焦点时状态
            focusedBorder:  const UnderlineInputBorder(borderSide: BorderSide.none), //有焦点时状态
            hintText: '请输入姓名',
            hintStyle: text_grey_14,
          ),
        ),
        const LineHorizontal(),
        TextField(
          controller: idController,
          style: text_131732_14,
          decoration: InputDecoration(
            prefixText: "  ",
            isDense: true,
            contentPadding: EdgeInsets.symmetric(vertical: 9.w),
            counterText: "", // 去掉底部计数
            enabledBorder:  const UnderlineInputBorder(borderSide: BorderSide.none), //无焦点时状态
            focusedBorder:  const UnderlineInputBorder(borderSide: BorderSide.none), //有焦点时状态
            hintText: '请输入身份证号',
            hintStyle: text_grey_14,
          ),
        ),
        const LineHorizontal(),
        SizedBox(height: 15.w),
      ],
    );
  }

  void toRequest() async {
    var name = nameController.text;
    var id = idController.text;
    if(name.isEmpty){
      EasyLoading.showToast('请填写真实的姓名');
      return;
    }
    if(id.isEmpty){
      EasyLoading.showToast('请填写真实的身份证号');
      return;
    }
    Map<String, dynamic> obj = {
      'identity_num' : id,
      'real_name' : name,
      'gender' : gender,
      'address' : address,
      'nation' : nation,
      'birthday' : birthDay,
      'issued_by' : issuedBy,
      'valid_date' : validDate,
      'front_image' : idFrontUrl.value,
      'back_image' : idBackUrl.value,
    };
    var result = await apiProvider.getData(obj, ApiProvider.updated_identity);
    if(result.code == 200){
      EasyLoading.showToast('保存成功');
      Get.back();
    }else{
      EasyLoading.showToast('${result.msg}');
    }
  }

  /// 扫描身份证
  void toScanIdCard(bool isFront) {
    Map<String, dynamic> map = {};
    map['is_front'] = isFront;
    platform.invokeMethod('scanIdCard',map);
  }
}
